package com.example.administrator.personalmail.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.print.PrinterId;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.example.administrator.personalmail.Activity.WebDetailActivity;
import com.example.administrator.personalmail.R;
import com.example.administrator.personalmail.adapter.HotAdapter;
import com.example.administrator.personalmail.api.Contants;
import com.example.administrator.personalmail.eventBean.HotPage;
import com.example.administrator.personalmail.model.Page;
import com.example.administrator.personalmail.model.Wares;
import com.example.administrator.personalmail.retrofitAPI.GetRequest_Interface;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2018/4/14 0014.
 */

public class FragmentTwo extends Fragment{
    private Page<Wares> mPage;
    private ArrayList<Wares> mWares;
    private HotAdapter mHotAdapter;
    private RecyclerView mRecyclerView;
    private MaterialRefreshLayout materialRefreshLayout;
    final private int PAGE_SIZE = 10;
    private int curPage=1;
    private int totalPage=0;
    private int REFRESH=1;
    private int LOADMORE=2;
    private int state=0;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_two,container,false);
        init(view);
        initShow();
        return view;
    }

    private void init(View view){
        mRecyclerView = view.findViewById(R.id.rvHot);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        materialRefreshLayout = view.findViewById(R.id.mrefresh);
        materialRefreshLayout.setLoadMore(true);
        materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                state=REFRESH;
                curPage=1;
                hotRerofit();
//                materialRefreshLayout.finishRefresh();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                if (curPage<=totalPage){
                    state=LOADMORE;
                    curPage++;
                    hotRerofit();
                }else {
                    materialRefreshLayout.finishRefreshLoadMore();
                }


            }
        });
    }

    private void initShow(){
        hotRerofit();

    }

    private void hotRerofit(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Contants.API.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        GetRequest_Interface service = retrofit.create(GetRequest_Interface.class);
        retrofit2.Call<Page<Wares>> call = service.hotRequest(curPage,PAGE_SIZE);
        call.enqueue(new retrofit2.Callback<Page<Wares>>() {
            @Override
            public void onResponse(retrofit2.Call<Page<Wares>> call, retrofit2.Response<Page<Wares>> response) {
                mPage = response.body();
                if (state == LOADMORE) {
                    mHotAdapter.addData(mHotAdapter.getSize(),mPage.getList());
                    if (curPage==totalPage){
                        mHotAdapter.setFOOTER(true);
                    }
                    materialRefreshLayout.finishRefreshLoadMore();
                }else if (state == REFRESH){
                    mWares = mPage.getList();
                    mHotAdapter = new HotAdapter(mWares,getContext());
                    mHotAdapter.setOnItemClickListener(new HotAdapter.ItemClickListenner() {
                        @Override
                        public void onItemClick(int position) {
                            Intent intent = new Intent(getActivity(), WebDetailActivity.class);
                            intent.putExtra("wares",mWares.get(position));
                            startActivity(intent);
                        }
                    });
                    mHotAdapter.setFOOTER(false);
                    mRecyclerView.setAdapter(mHotAdapter);
                    materialRefreshLayout.finishRefresh();
                }else {
                    mWares = mPage.getList();
                    mHotAdapter = new HotAdapter(mWares,getContext());
                    mHotAdapter.setOnItemClickListener(new HotAdapter.ItemClickListenner() {
                        @Override
                        public void onItemClick(int position) {
                            Intent intent = new Intent(getActivity(), WebDetailActivity.class);
                            intent.putExtra("wares",mWares.get(position));
                            startActivity(intent);
                        }
                    });
                    mRecyclerView.setAdapter(mHotAdapter);

                    if (totalPage==0){
                        int page = mPage.getTotalCount()/10;
                        if (mPage.getTotalCount()%10 != 0){
                            totalPage = page+1;
                        }else {
                            totalPage = page;
                        }
                    }
                }

            }

            @Override
            public void onFailure(retrofit2.Call<Page<Wares>> call, Throwable t) {
                Log.e("---------","error");

            }
        });
    }





    //    okhttp请求，gson直接解析有问题，弃用
    private void hotWaresRequest() {
        String url = Contants.API.WARES_HOT+"?curPage="+curPage+"&pageSize="+PAGE_SIZE;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("---------",response.body().string());
                String json = response.body().string();
                Gson gson = new Gson();
                Type type = new TypeToken<Page<Wares>>(){}.getType();
                mPage = gson.fromJson(json,type);
                mWares = mPage.getList();
                EventBus.getDefault().post(new HotPage());
            }
        });
    }

}
